<template>
	<view class="content">
		<uni-forms :modelValue="form" ref="form" :rules="rules">
			<uni-forms-item name="sendUser" required label="联系人">
				<uni-easyinput v-model="form.sendUser" type="text" placeholder="请输入联系人" />
			</uni-forms-item>
			<uni-forms-item required label="手机号" name="sendPhone">
				<uni-easyinput type="number" v-model="form.sendPhone" maxlength="11" placeholder="请输入手机号" />
			</uni-forms-item>
			<!-- <uni-forms-item required name="adcode" label="省市区">
				<view style="display: flex;justify-content: space-between;">
					<uni-data-picker v-model="form.adcode" :localdata="items" popup-title="请选择省份" @change="onchange"
						style="width: 88%;" />
					<uni-icons @tap.stop="openMAP" type="map-pin-ellipse" size="30" color="orange" />
				</view>
			</uni-forms-item> -->
			<uni-forms-item required label="取件地址" label-width="100">
				<!-- @tap.stop="openMAP" -->
				<view @click="jumpMap" class="map"  v-if="!form.detailAddress">
					<uni-icons type="map-pin-ellipse" size="30" color="orange" />请选择取件地址
				</view>
				<view class="" style="display: flex;" v-else>
					<view class="" style="flex: 1;font-size: 24rpx;width: 300rpx;">
						<view class="" style="width: 100%;font-weight: bold;font-size: 30rpx;margin-bottom: 10rpx;">
							{{form.addressName}}
						</view>
						<view class="" style="width: 100%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
							{{form.detailAddress}}
						</view>
						
					</view>
					<view class="" style="color: #fe7002;margin-left: 20rpx;display: flex;align-items: center;justify-content: center;" @click="jumpMap">
						修改地址
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="detailAddress" required label="详细地址" label-width="100">
				<uni-easyinput v-model="form.areaAddress" type="textarea"
					placeholder="详细地址，楼号和门牌号"  />
					<!-- @input="searchVal" @focus="warn" -->
			</uni-forms-item>
		</uni-forms>
		<!-- <view style="display: flex;justify-content:flex-end;">
			<view class="" @click="jumpAddress">
				<image src="/static/images/address/address.png" mode="" class="img"></image>
				地址簿
			</view>
		</view> -->
		<view class="body2" @click="submit">确定</view>
	</view>
</template>

<script>
	import {
		proCityList
	} from '@/util/city.js'
	import util from '@/util/util.js'
	import {
		redeemGifts
	} from '@/api/user.js'
	import QQMapWX from '@/libs/qqmap-wx-jssdk.min.js'
	// import * as amapFile from '@/libs/amap-wx.130';
	export default {
		data() {
			return {
				ani: true,
				mapCtx: null,
				mapObj: null,
				key: 'K2IBZ-FU5YB-ZTKUK-JP4EG-VU5T7-FAFPO',
				qqmapsdk: null,
				scrollH: 0,
				address: [],
				timer: null,
				keywords: '车站',
				location: null,
				pageIndex: 1,
				loading: false,
				pullUpOn: true,
				scrollTop: 0,
				index: -1,
				isClick: false, //选择地址防止app端刷新地址
				changeTimer: null,
				areaDate: [],
				identification: 0,
				items: proCityList,
				form: {
					sendUser: '',
					name: "",
					sendPhone: "",
					detailAddress: "",
					adcode: "",
					province: '',
					city: '',
					longitude: '',
					latitude: '',
					addressName:'',
					
				},
				
				flag: false,
				searchFlag: false,
				textData: {
					longitude: '',
					latitude: '',
					name: '', // 名称
					address: '', // 详细地址
					province: '', // 省份
					city: '', // 城市
					district: '', // 区县
				},
				result: [],
				giveaddress:{}
			}
		},
		mounted() {},
		onLoad(options) {
			console.log(options)
			if(options.item){
				this.giveaddress = JSON.parse(options.item)
			}
			
			if (uni.getStorageSync('form')) {
				console.log("缓存对象==========", uni.getStorageSync('form'))
				let formObject = uni.getStorageSync('form')
				this.form.sendUser = formObject.sendUser
				this.form.sendPhone = formObject.sendPhone
				this.form.detailAddress = formObject.detailAddress
				this.form.province = formObject.province
				this.form.adcode = formObject.adcode
				this.form.city = formObject.city
				this.textData.latitude = formObject.latitude
				this.textData.longitude = formObject.longitude
			}

		},
		onShow() {
			console.log(12)
			var sendAddress = uni.getStorageSync('sendAddress')
			if(sendAddress){
				this.form.detailAddress = sendAddress.province + sendAddress.city + sendAddress.district+ sendAddress.address
				this.form.addressName = sendAddress.name
				this.form.province = sendAddress.province
				this.form.adcode = sendAddress.adcode
				this.form.city = sendAddress.city
				let location = sendAddress.location.split(",")
				this.textData.latitude = location[1]
				this.textData.longitude = location[0]
				uni.removeStorageSync('sendAddress')
			}
		},
		methods: {
			jumpMap(){
				uni.navigateTo({
					url:"/pages/map/map"
				})
			},
			openMAP() {
				// setTimeout(() => {
				let sys = uni.getSystemInfoSync();
				this.scrollH = sys.windowHeight - uni.upx2px(600) - 46; //78=30+8*2
				this.qqmapsdk = new QQMapWX({
					key: this.key
				});
				this.currentLocation();
				// }, 80);
				setTimeout(() => {
					this.flag = true
				}, 100)

			},
			choose(index) {
				if (this.result.length === 0) return;
				let item = this.result[index];
				console.log(item);
				this.textData.latitude = item.location.lat
				this.textData.longitude = item.location.lng
				this.form.detailAddress = item.address + '-' + item.name
				this.searchFlag = false
			},
			jumpAddress() {
				uni.$tui.href(`/pages/address/address?type=1`);
			},
			calculateDistance(to, callback) {
				this.qqmapsdk.calculateDistance({
					from: '', //默认当前位置
					to: to,
					success: res => {
						callback && callback(res.result);
					},
					fail: res => {
						callback && callback(false);
						console.log(res);
					}
				});
			},
			getPoiAround() {
				if (!this.keywords) return;
				this.pageIndex = 1;
				this.pullUpOn = true;
				this.address = [];
				this.index = -1;
				this.scrollTop = 1;
				setTimeout(() => {
					this.scrollTop = 0;
				}, 10);
				this.getLocation(this.keywords);
			},
			regionchange(e) {
				let isEnd = e.type == 'end';
				// #ifdef APP-PLUS || MP-WEIXIN
				isEnd = e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag');
				// #endif
				if (isEnd) {
					clearTimeout(this.timer);
					this.ani = false;
					this.timer = setTimeout(() => {
						this.ani = true;
					}, 300);
					if (!this.mapCtx) {
						this.mapCtx = uni.createMapContext('maps');
					}
					this.mapCtx.getCenterLocation({
						type: 'gcj02',
						success: res => {
							this.textData.latitude = res.latitude;
							this.textData.longitude = res.longitude;
							this.getAddress(res.longitude, res.latitude);
						}
					});
				}
			},
			getAddress(lng, lat) {
				// #ifdef H5
				let url =
					`https://apis.map.qq.com/ws/geocoder/v1/?location=${lat + ',' + lng}&key=${this.key}&get_poi=0&callbackName=QQmap&output=jsonp&coord_type=5`;
				uni.$tui.tuiJsonp(
					url,
					res => {
						if (res.status === 0) {
							this.keywords = res.result.formatted_addresses.recommend;
							this.getPoiAround();
						}
					},
					'QQmap'
				);
				// #endif

				// #ifndef H5
				//根据经纬度获取地址信息
				this.qqmapsdk.reverseGeocoder({
					location: {
						latitude: lat,
						longitude: lng
					},
					success: res => {
						this.keywords = res.result.formatted_addresses.recommend;
						this.getPoiAround();
					},
					fail: res => {
						this.keywords = '车站';
						this.getPoiAround();
					}
				});
				// #endif
			},
			// async getLocation(){
			//  let _this =this;
			// 	uni.getLocation({
			// 		type: 'gcj02',
			// 		isHighAccuracy: true,
			// 		success: function (res) {
			// 			console.log('当前位置的经度：' + res.longitude);
			// 			console.log('当前位置的纬度：' + res.latitude);
			// 			_this.formCo.latitude=  parseFloat( res.latitude);
			// 	        _this.formCo.longitude=parseFloat(res.longitude);  
			// 			console.log('当前位置的经度：' + _this.form);
			// 			_this.orientation();
			// 		},
			// 	});
			// },
			currentLocation() {
				//当前位置
				const that = this;
				uni.getLocation({
					// #ifdef APP-PLUS || MP-WEIXIN
					type: 'gcj02',
					// #endif
					altitude: true,
					success(res) {
						that.textData.latitude = res.latitude;
						that.textData.longitude = res.longitude;
						that.getAddress(res.longitude, res.latitude);
					},
					fail(res) {
						that.getAddress(that.textData.longitude, that.textData.latitude);
					}
				});
			},
			getLocation() {
				if (!this.pullUpOn || this.loading) return;
				this.loading = true;
				let keywords = this.keywords;
				let index = keywords.indexOf('(');
				if (index !== -1) {
					keywords = keywords.substring(0, index);
				}
				// #ifdef H5
				//https://lbs.qq.com/webservice_v1/guide-suggestion.html
				let url =
					`https://apis.map.qq.com/ws/place/v1/suggestion?keyword=${keywords}&location=${this.textData.latitude +
				',' +
				this.textData.longitude }&region_fix=1&policy=0&page_size=10&page_index=${this.pageIndex}&get_subpois=1&output=jsonp&key=${this.key}`;
				uni.$tui.tuiJsonp(
					url,
					res => {
						if (res.status === 0) {
							let data = res.data || [];
							this.calculateDistance(data, d => {
								if (d) {
									let arr = d.elements || [];
									for (let i = 0, len = data.length; i < len; i++) {
										data[i].distance = arr[i].distance;
									}
								}
								this.address = this.address.concat(data);
								this.pageIndex++;
								this.loading = false;
								if (data.length < 10) {
									this.pullUpOn = false;
								}
							});
						}
					},
					'QQmap'
				);
				// #endif

				// #ifndef H5
				this.qqmapsdk.getSuggestion({
					keyword: keywords,
					page_index: this.pageIndex,
					location: {
						latitude: this.textData.latitude,
						longitude: this.textData.longitude
					},
					success: res => {
						let data = res.data || [];
						this.calculateDistance(data, d => {
							if (d) {
								let arr = d.elements || [];
								for (let i = 0, len = data.length; i < len; i++) {
									data[i].distance = arr[i].distance;
								}
							}
							this.address = this.address.concat(data);
							this.pageIndex++;
							this.loading = false;
							if (data.length < 10) {
								this.pullUpOn = false;
							}
						});
					},
					fail: res => {
						this.loading = false;
						console.log(res);
					}
				});
				// #endif
			},
			submit() {
				console.log(this.textData);
				this.form.latitude = this.textData.latitude
				this.form.longitude = this.textData.longitude
				this.flag = false
				console.log(this.giveaddress)
				let {sendUser,sendPhone,longitude,addressName,detailAddress,latitude,areaAddress} = this.form
				
				
				
				
				let {name,number} = this.giveaddress
				let params = {
					gift: name,
					count: number,
					receiverName: sendUser,
					receiverPhone: sendPhone,
					receiverAddr: detailAddress + addressName + areaAddress,
					receiverLongitude: longitude,
					receiverLatitude: latitude
				}
				console.log(params)
				if(!sendUser){
					uni.showToast({
						title: '请填写联系人',
						icon: 'none'
					})
					return
				}
				if(!sendPhone){
					uni.showToast({
						title: '请填写手机号',
						icon: 'none'
					})
					return
				}
				if(!detailAddress){
					uni.showToast({
						title: '请选择地址',
						icon: 'none'
					})
					return
				}
				if(!areaAddress){
					uni.showToast({
						title: '请填写详细地址',
						icon: 'none'
					})
					return
				}
				
				
				
				
				
				
				// uni.showToast({
				// 	title: "兑换成功",
				// 	icon: "none"
				// })
				// return
				redeemGifts(params, 'post')
					.then((res) => {
						console.log(res)
						if(res.code == 200){
							uni.showToast({
								title: "兑换成功",
								icon: "none"
							})
							let settime = setTimeout(()=>{
								uni.navigateBack()
								clearTimeout(settime)
							},1000)
							
						}
					})
					.catch((err)=>{
						console.log(err)
					})
				// uni.showLoading()
				// this.$refs.form.validate().then(res => {
				// 	uni.hideLoading()
				// 	console.log('表单数据信息：', this.form);
				// 	this.form.detailAddress = this.form.detailAddress + this.form.addressName + this.form.areaAddress
				// 	//写入缓存
				// 	uni.setStorageSync('form', this.form);
				// 	uni.switchTab({
				// 		url: "/pages/expressPages/expressPages"
				// 	})
				// }).catch(err => {
				// 	uni.hideLoading()
				// 	console.log('表单错误信息：', err);
				// })
			}
		}
	}
</script>
<style lang="scss" scoped>
	.map{
		background: rgb(255, 255, 255);
		color: rgb(255, 143, 0);
		box-shadow: none;
		border: 1px solid rgb(255, 143, 0) !important;
		border-radius: 50px;
		padding: 6px;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.tui-list-view {
		height: 250px;
		overflow: auto;
	}

	.img {
		width: 20px;
		height: 20px;
	}

	.content {
		position: relative;
		padding: 10px;
		background-color: #fff;
		height: -webkit-fill-available;
	}

	.body2 {
		height: 100rpx;
		width: 700rpx;
		margin: 30rpx auto;
		border-radius: 30rpx;
		box-shadow: 5px 5px 10px rgb(227, 242, 204);
		background: rgb(204, 255, 1);
		text-align: center;
		line-height: 100rpx;
		font-weight: bold;
		color: rgb(254, 112, 2);
	}

	.container {
		background-color: #fff;
		position: absolute;
		top: 0;
		/* 底部留出的空间 */
		left: 0;
		right: 0;
		z-index: 999;
	}

	.tui-maps {
		width: 100%;
		min-width: 750rpx;
		height: 600rpx;
	}

	.tui-cover-image {
		width: 60rpx;
		height: 60rpx;
		position: fixed;
		top: 300rpx;
		left: 50%;
		margin-top: -60rpx;
		margin-left: -30rpx;
		z-index: 10;
	}

	.tui-ani {
		animation: ani 0.4s linear;
	}

	@-webkit-keyframes ani {
		0% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-50rpx);
		}

		100% {
			transform: translateY(0);
		}
	}

	.tui-current-img {
		width: 76rpx;
		height: 76rpx;
		border-radius: 50%;
		box-shadow: 0 15rpx 10rpx -15rpx #bbb;
		position: fixed;
		top: 470rpx;
		right: 40rpx;
		z-index: 10;
	}

	.tui-cover-back {
		width: 60rpx;
		height: 60rpx;
		position: fixed;
		/* #ifdef H5 */
		top: 30rpx;
		/* #endif */
		/* #ifndef H5 */
		top: 60rpx;
		/* #endif */
		left: 30rpx;
	}

	.tui-search__box {
		width: 100%;
		padding: 10px 30rpx;
		box-sizing: border-box;
	}

	.thorui-flex__center {
		width: 100%;
		height: 30px;
		background-color: #f2f2f2;
		border-radius: 4px;
	}

	.tui-search__text {
		padding-left: 20rpx;
		font-size: 13px;
		line-height: 13px;
		color: #999;
	}

	.tui-list__item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.tui-addr-box {
		flex: 1;
		max-width: 88%;
	}

	.tui-addr-title {
		width: 100%;
		font-size: 34rpx;
		line-height: 36rpx;
		color: #222;
		padding-bottom: 12rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tui-addr-detail {
		width: 100%;
		font-size: 26rpx;
		color: #999;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tui-distance {
		color: #5677fc;
		padding-right: 8rpx;
	}

	.tui-label__width {
		width: 100%;
	}

	.thorui-radio {
		padding-bottom: 96rpx;
	}

	.tui-radio-box {
		flex-shrink: 0;
	}

	.tui-seize__seat {
		width: 100%;
		height: env(safe-area-inset-bottom);
	}

	.tui-btn__box {
		width: 100%;
		background-color: #fff;
		padding: 12rpx 30rpx;
		box-sizing: border-box;
		font-size: 24rpx;
		color: #666;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 10;
		box-shadow: 0 0 1px rgba(0, 0, 0, 0.5);
		-webkit-backface-visibility: hidden;
	}

	.tui-search__bar {
		width: 100%;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		background-color: #ffffff;
		position: relative;
	}

	.tui-search__bar::after {
		content: '';
		position: absolute;
		width: 100%;
		height: 1rpx;
		left: 0;
		bottom: 0;
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
		transform: scaleY(0.5);
	}

	.tui-search__box {
		width: 100%;
		height: 72rpx;
		background-color: #f2f2f2;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		padding-left: 24rpx;
		box-sizing: border-box;
	}

	.tui-icon__search {
		flex-shrink: 0;
		margin-right: 8rpx;
	}

	.tui-search__input {
		flex: 1;
		font-size: 28rpx;
	}

	.tui-icon__clear {
		width: 60rpx;
		height: 100%;
		padding: 0 10rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.tui-btn__search {
		flex-shrink: 0;
		height: 100%;
		padding: 0 24rpx;
		margin-left: auto;
		font-size: 28rpx;
		color: #5677fc;
		display: flex;
		align-items: center;
		position: relative;
	}

	.tui-btn__search::before {
		content: '';
		position: absolute;
		height: 40%;
		border-left: 1rpx solid #999;
		top: 30%;
		left: 0;
	}

	.tui-addr__box {
		width: 100%;
		padding: 0 30rpx 0 12rpx;
		box-sizing: border-box;
	}

	.tui-addr-title {
		flex: 1;
		font-size: 34rpx;
		color: #222;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tui-addr-detail {
		flex: 1;
		font-size: 26rpx;
		color: #999;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		padding: 8rpx 0;
	}

	.tui-tag {
		display: inline-flex;
		padding: 6rpx 20rpx;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999;
		border: 1rpx solid #999;
		border-radius: 30rpx;
	}
</style>